<?php

include_once "baseChannel.php";
// 时间相差8小时
date_default_timezone_set("Asia/Shanghai");
class haiyi extends BaseChannel
{

    // protected $appId;
    protected $appSecret;

    // 辅助加密参数
    public function __construct($options)
    {
        parent::__construct($options);
        $this->appSecret =  $options['appSecret'];
        $this->cid = $options['cid'];
    }
    // 计算签名提单需要签名
    public function getSign($data)
    {
        // 排序
        $newData['app_id'] = $data['app_id'];
        $newData['cid'] = $this->cid;
        $newData['phone'] = $data['phone'];
        $newData['key'] = $this->appSecret;
        $newData = http_build_query($newData);
        $sign = md5($newData);
        return $sign;
    }

    public function queryBalance($params = [])
    {
        $data = [];
        $data['cid'] = $this->cid;
        $url = $this->query_balance_url . '?' . http_build_query($data);
        $return_str = $this->httpRequest($url, 'GET');
        $return_data = json_decode($return_str, 1);
        if ($return_data['ResultCode'] == 0) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['overp'] ?? 0, //余额
                'credit' => 0, //授信 creditQuota
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['overp'] ?? '查询失败',
            'code' => 500
        ];
    }
    //上游支持多订单查询，这里同步成单笔订单
    public function queryOrder($params)
    {
        $data = [
            [
                'id' => $params['push_order_sn']
            ],
        ];
        $data = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $url = $this->query_order_url . '/' . $this->cid;
        $return_str = $this->httpRequest($url, 'POST', $data, '', '', $headerArray);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => $data, //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //处理中
        if ($return_data['code'] == 200 && $return_data['result'][0]['status'] == 3) {
            $ret['msg'] = '充值中';
        }
        // 成功
        if ($return_data['code'] == 200 && $return_data['result'][0]['status'] == 1) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['result'][0]['msg'];
        }
        // 失败
        if ($return_data['code'] == 200 && $return_data['result'][0]['status'] == 2) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['result'][0]['msg'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $data = [];
        $data['app_id'] = $code;   //产品id
        $data['clecs'] = $params['isp']; //运营商
        $data['cid'] = $this->cid;
        $data['phone'] = $mobile;
        $data['order_id'] = $params['push_order_sn'];
        $data['timestamp'] = $this->getCurDate(true);
        $data['callbackurl'] = $this->callback_url;
        $data['sign'] = $this->getSign($data);
        $url = $this->submit_order_url . '?' . http_build_query($data);
        //
        // file_put_contents("../api_resource/logs/" . date("Ymd") . "queuedata.log", json_encode($data) . PHP_EOL, FILE_APPEND);
        $return_str = $this->httpRequest($url, 'GET');
        $return_data = json_decode($return_str, 1);
        $ret = [
            'url' => $url,
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['TransactionID'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' => null,
            'channel_balance' => null,
        ];
        // var_dump($return_data);
        if ($return_data['ResultCode'] == 0) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['ResultDesc'] ?? '下单成功';
        } else {
            if (isset($return_data['ResultCode'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['ResultDesc'] ?? '下单失败';
            }
        }
        return $ret;
    }
    public function callback($params)
    {
        $this->callback_params = $params;
        $params = json_decode($params['json'], true);
        $this->channel_order_sn = $params['TransactionID'];
        $this->push_order_sn = $params['order_id'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $params['Status'];
        $msg = $params['msg'];
        //凭证
        $pz =  '';
        // 验证签名
        $signRes = $this->decrypt($params);
        if (!$signRes) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            return $res;
        }
        if ($order_status == 1) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = 'success';
        }
        if ($order_status == 2) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }
        if ($order_status == 3) {
            $res['order_status'] = 2;
            $res['msg'] = $msg ?? '充值中';
        }
        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = date('YmdHis') . substr($time, -3);
            return $timestamp;
        }
    }
    public function decrypt($data)
    {
        $newData = [
            'cid' => $this->cid,
            'phone' => $data['phone'],
            'key' => $this->appSecret,
        ];
        $newSign = md5(http_build_query($newData));
        if ($newSign == $data['sign']) {
            return true;
        } else {
            return false;
        }
    }
}
